CC	= mpic++
MPICC	= mpic++

SRCEXTS	= .cpp
HDREXTS	= .h
OBJEXT	= .o

CFLAGS	= -O2 -Wall -Iinclude -fopenmp
LDFLAGS	= -fopenmp -lm -lrt

SRCDIR	= src
INCDIR	= include
MDIR	= main
OBJDIR	= bin

MAIN	= $(MDIR)/main$(SRCEXTS)

MOBJ1	= $(OBJDIR)/$(MDIR)/main_seq.o
MOBJ2	= $(OBJDIR)/$(MDIR)/main_mp.o
MOBJ3	= $(OBJDIR)/$(MDIR)/main_mpi.o
MOBJ4	= $(OBJDIR)/$(MDIR)/main_both.o

PROGRAM1 = palin_seq
PROGRAM2 = palin_mp
PROGRAM3 = palin_mpi
PROGRAM4 = palin_both

SOURCES = $(foreach d,$(SRCDIR),$(wildcard $(addprefix $(d)/*,$(SRCEXTS))))
MAINS 	= $(foreach d,$(MDIR),$(wildcard $(addprefix $(d)/*,$(SRCEXTS))))
HEADERS = $(foreach d,$(INCDIR),$(wildcard $(addprefix $(d)/*,$(HDREXTS))))
OBJS    = $(addsuffix .o, $(addprefix $(OBJDIR)/, $(basename $(SOURCES))))
MOBJS	= $(addsuffix .o, $(addprefix $(OBJDIR)/, $(basename $(MAINS))))

.PHONY: all objs clean clean_all show exec
.SUFFIXES:

all: $(PROGRAM1) $(PROGRAM2) $(PROGRAM3) $(PROGRAM4)

objs: $(OBJS)

$(OBJDIR)/%$(OBJEXT):%$(SRCEXTS) $(HEADERS)
	mkdir $(dir $@) -p
	$(CC) -c $< -o $@ $(CFLAGS)
	
$(PROGRAM1):$(OBJS)
	mkdir $(dir $(MOBJ1)) -p
	$(CC) -c $(MAIN) -o $(MOBJ1) $(CFLAGS)
	$(CC) $(OBJS) $(MOBJ1) -o $(OBJDIR)/$@ $(LDFLAGS)
	@echo Type \'make exec_seq_wiki\' or \'make exec_seq_shak\' to execute.

$(PROGRAM2):$(OBJS)
	mkdir $(dir $(MOBJ2)) -p
	$(CC) -c $(MAIN) -o $(MOBJ2) $(CFLAGS) -D_USING_MP
	$(CC) $(OBJS) $(MOBJ2) -o $(OBJDIR)/$@ $(LDFLAGS)
	@echo Type \'make exec_mp_wiki\' or \'make exec_mp_shak\' to execute.
	
$(PROGRAM3):$(OBJS)
	mkdir $(dir $(MOBJ3)) -p
	$(CC) -c $(MAIN) -o $(MOBJ3) $(CFLAGS) -D_USING_MPI
	$(CC) $(OBJS) $(MOBJ3) -o $(OBJDIR)/$@ $(LDFLAGS)
	@echo Type \'make exec_mpi_wiki\' or \'make exec_mpi_shak\' to execute.
	
$(PROGRAM4):$(OBJS)
	mkdir $(dir $(MOBJ4)) -p
	$(CC) -c $(MAIN) -o $(MOBJ4) $(CFLAGS) -D_USING_MP -D_USING_MPI
	$(CC) $(OBJS) $(MOBJ4) -o $(OBJDIR)/$@ $(LDFLAGS)
	@echo Type \'make exec_both_wiki\' or \'make exec_both_shak\' to execute.
	
clean:
	find bin -iname *$(OBJEXT) -delete
	
clean_all:
	rm -R $(OBJDIR)

exec_seq_wiki:
	./$(OBJDIR)/$(PROGRAM1) data/wikipedia.txt 1

exec_seq_shak:
	./$(OBJDIR)/$(PROGRAM1) data/shakespe.txt 2
	
exec_mp_wiki:
	./$(OBJDIR)/$(PROGRAM2) data/wikipedia.txt 1

exec_mp_shak:
	./$(OBJDIR)/$(PROGRAM2) data/shakespe.txt 2
	
exec_mpi_wiki:
	mpirun -hostfile hosts ./$(OBJDIR)/$(PROGRAM3) data/wikipedia.txt 1

exec_mpi_shak:
	mpirun -hostfile hosts ./$(OBJDIR)/$(PROGRAM3) data/shakespe.txt 2
	
exec_both_wiki:
	mpirun -hostfile hosts ./$(OBJDIR)/$(PROGRAM4) data/wikipedia.txt 1

exec_both_shak:
	mpirun -hostfile hosts ./$(OBJDIR)/$(PROGRAM4) data/shakespe.txt 2

show:
	@echo 'SRCDIR      :' $(SRCDIR)
	@echo 'INCDIR      :' $(INCDIR)
	@echo 'MDIR        :' $(MDIR)
	@echo 'OBJDIR      :' $(OBJDIR)
	@echo 'SOURCES     :' $(SOURCES)
	@echo 'MAINS       :' $(MAINS)
	@echo 'HEADERS     :' $(HEADERS)
	@echo 'OBJS        :' $(OBJS)
	@echo 'MOBJS       :' $(MOBJS)
	@echo 'CFLAGS      :' $(CFLAGS)
	@echo 'LDFLAGS     :' $(LDFLAGS)
	
